package com.ehi.common.jersey.status;

import com.ehi.common.jersey.AbstractApplication;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;

public class TestApplication extends AbstractApplication {

    @Override
    protected void registerApis() {
        this.register(TestResource.class);
    }

    @Override
    protected void registerComponents() {
        this.property("contextConfigLocation", "classpath:applicationContext.xml");
    }

    @XmlRootElement
    public static class TestObject implements Serializable {

        private static final long serialVersionUID = 2118336123369478889L;

        private String info;

        // For serialize/deserialize json
        public TestObject() {
        }

        public TestObject(String info) {
            this.info = info;
        }

        public String getInfo() {
            return info;
        }

        // For serialize/deserialize json
        public void setInfo(String info) {
            this.info = info;
        }

    }

    public static class TestService {

        public String shouldThrowException() throws Exception {
            throw new Exception("inner exception");
        }

    }

    @Path("/test")
    public static class TestResource {

        @GET
        @Path("/{param}")
        @Produces(MediaType.APPLICATION_JSON)
        public Response getResource(@PathParam("param") String param) {
            // Invalid request parameter
            if ("invalid".equals(param)) {
                return ResponseBuilder.badRequest("param is invalid");
            }

            if ("invalid2".equals(param)) {
                throw new IllegalArgumentException("bad request");
            }

            // resource not found.
            if ("notfound".equals(param)) {
                return ResponseBuilder.notFoundObject();
            }

            if ("single".equals(param)) {
                return ResponseBuilder.okForSingleValue("key", "value");
            }

            // exception occurred.
            if ("exception".equals(param)) {
                try {
                    new TestService().shouldThrowException();
                } catch (Exception e) {
                    throw new IllegalStateException("exception message", e);
                }
            }

            return ResponseBuilder.ok(new TestObject("success"));
        }

        @POST
        @Path("/post")
        @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
        @Produces(MediaType.APPLICATION_JSON)
        public Response postResource(@FormParam("param") String param) {
            return ResponseBuilder.ok(new TestObject("success"));
        }

    }
}
